import json
import os
import uuid
from datetime import datetime

from django.core.paginator import Paginator, EmptyPage

# Create your views here.
from django.views import View
from homes.models import House, Area, Facility, HouseImage
from django.http import JsonResponse

from ihome.utils.qiniu import qiniuimg
from order.models import Order
from users.utils import LoginRequiredJSONMixin
from users.views import logger


class AreasListView(View):
    def get(self, request):
        house_objs = Area.objects.all()
        if not house_objs:
            return JsonResponse({'errno': 4002, 'errmsg': '无数据'})
        house_list = []
        for house in house_objs:
            house_list.append({
                'aid': house.id,
                'aname': house.name
            })
        return JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': house_list})


class CreateHousesView(View):
    def get(self, request):
        aid = request.GET.get('aid')
        start_day = request.GET.get('sd')
        end_day = request.GET.get('ed')
        sort_key = request.GET.get('sk')
        houses_objs = House.objects.filter(status=House.HOUSE_STATUS.get('NOT_SCHEDULED'))
        houses_objs_list = []

        if aid:
            houses_objs = houses_objs.filter(area_id=aid)

        # TODO:时间比对判断
        if sort_key:
            if sort_key == 'booking':
                houses_objs = houses_objs.order_by('-order_count')
            elif sort_key == 'price-inc':
                houses_objs = houses_objs.order_by('price')
            elif sort_key == 'price-des':
                houses_objs = houses_objs.order_by('-price')
            else:
                houses_objs = houses_objs.order_by('-create_time')

        # TODO:根据时间获取房源信息
        if start_day:
            time_start_day = datetime.strptime(start_day, "%Y-%m-%d")
            print(type(time_start_day))
            # houses_objs = houses_objs.filter(create_time__gte=time_start_day)
            for house in houses_objs:
                # ctime = datetime.strftime(time_start_day,"%Y-%m-%d") # 时间转换成字符串
                # ctime = datetime.strptime(ctime,"%Y-%m-%d") # 时间对象
                # diff = time_start_day - ctime
                ctime = datetime.strftime(house.create_time, "%Y-%m-%d")
                print(type(ctime), ctime)
                ctime = datetime.strptime(ctime, "%Y-%m-%d")
                print(type(ctime), ctime)
                diff = time_start_day - ctime
                if diff.days > 0:
                    houses_objs_list.append(house)
                elif diff.days == 0 and diff.seconds >= 0:
                    houses_objs_list.append(house)
        if end_day:
            time_end_day = datetime.strptime(sort_key, "%Y-%m-%d")
            # houses_objs = houses_objs.filter(create_time__ite=time_sort_key)
            for house in houses_objs:
                ctime = datetime.strftime(house.create_time,"%Y-%m-%d")
                print(type(ctime), ctime)
                ctime = datetime.strptime(ctime,"%Y-%m-%d")
                print(type(ctime), ctime)
                diff = time_end_day - ctime
                print(type(diff), diff)
                if diff.days < 0:
                    houses_objs_list.append(house)


        # TODO:分页查询
        page = request.GET.get('p')
        per_page = 5

        if not page:
            page = 1
        if not end_day or not start_day:
            paginator = Paginator(houses_objs,per_page)
            print(houses_objs)
        else:
            paginator = Paginator(houses_objs_list,per_page)

        try:
            page_houses = paginator.page(page)
        except EmptyPage as e:
            logger.error(e)
            return JsonResponse({
                'errno': 4501,
                'errmsg': '未知错误'
            })

        houses_list = []
        for house in page_houses:
            try:
                user_avatar = house.user.avatar.url
            except ValueError as e:
                logger.error(e)
                user_avatar = ''
            houses_list.append({
                "address": house.acreage,
                "area_name": house.area.name,
                "ctime": str(house.create_time).split(' ')[0],
                "house_id": house.id,
                "img_url": house.index_image_url.url,
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": user_avatar
            })
        total_page = paginator.num_pages
        return JsonResponse({'data': {'houses': houses_list, 'total_page': total_page}, 'errmsg': '请求成功', 'errno': '0'})

    def post(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({
                'errno': 4101, 'errmsg': '未登录'
            })
        data = json.loads(request.body.decode('utf-8'))
        title = data.get('title')
        price = data.get('price')
        area_id = data.get('area_id')
        address = data.get('address')
        room_count = data.get('room_count')
        acreage = data.get('acreage')
        unit = data.get('unit')
        capacity = data.get('capacity')
        deposit = data.get('deposit')
        min_days = data.get('min_days')
        max_days = data.get('max_days')
        facility = data.get('facility')
        if not all([title, price, area_id, address, room_count, acreage, unit, capacity, deposit, min_days, max_days,
                    facility]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少重要参数'})
        user = request.user
        try:
            house = House.objects.create(
                user_id=user.id,
                area_id=area_id,
                title=title,
                price=price,
                address=address,
                room_count=room_count,
                acreage=acreage,
                unit=unit,
                capacity=capacity,
                deposit=deposit,
                min_days=min_days,
                max_days=max_days,
                # facility_id__in=facility
            )
            # TODO:未知
            facilities = Facility.objects.filter(pk__in=facility)
            for f in facilities:
                house.facility.through.objects.create(house=house, facility=f)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004, 'errmsg': '数据错误'})
        return JsonResponse({"errno": "0", "errmsg": "发布成功", "data": {"house_id": house.id}})


class HousesImagesView(LoginRequiredJSONMixin, View):
    def post(self, request, house_id):
        img_file = request.FILES.get("house_image")
        if not img_file:
            return JsonResponse({'errno': 4103, 'errmsg': '缺少重要参数'})
        file_content = img_file.read()
        file_name = str(uuid.uuid4())
        file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), f'image/{file_name}.jpg')
        with open(file_path, 'wb') as f:
            f.write(file_content)

        ret_key = qiniuimg(file_name, file_path)

        try:
            house = House.objects.get(pk=house_id)
        except House.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({
                'errno': 4011,
                'errmsg': '数据库查询错误'
            })
        try:
            # TODO:图片上传
            house.index_image_url = ret_key
            house.save()
        except House.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({
                'errno': 4011,
                'errmsg': '数据库修改错误'
            })

        try:
            HouseImage.objects.create(
                url=ret_key,
                house=house
            )
        except House.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({
                'errno': 4011,
                'errmsg': '数据库修改错误'
            })

        house = House.objects.get(pk=house_id)
        house_url = house.index_image_url.url

        if os.path.exists(file_path):
            os.remove(file_path)
        else:
            return JsonResponse({
                'errno': 4011,
                'errmsg': '数据库修改错误'
            })

        return JsonResponse({
            'data': {
                'url': house_url
            },
            'errno': 0,
            'errmsg': '图片上传成功'

        })


class MyHouseView(LoginRequiredJSONMixin, View):
    def get(self, request):
        user = request.user
        house_objs = House.objects.filter(user_id=user.id)
        # if not house_objs:
        #     return JsonResponse({'errno': 4002, 'errmsg': '无数据'})
        house_list = []
        for house in house_objs:
            try:
                avatar_url = house.user.avatar.url
            except ValueError as e:
                logger.error(e)
                avatar_url = ''
            try:
                img_url = house.index_image_url.url
            except ValueError as e:
                logger.error(e)
                img_url = ''

            house_list.append({
                "address": house.acreage,
                "area_name": house.area.name,
                # "ctime": house.create_time,
                "ctime": str(house.create_time).split(' ')[0],
                "house_id": house.id,
                "img_url": img_url,
                "order_count": house.order_count,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                # "status": house.status,
                "user_avatar": avatar_url
            })
        return JsonResponse({'data': {'houses': house_list}, "errmsg": "ok", "errno": "0"})


class HouseIndexView(View):
    def get(self, request):
        houses_objs = House.objects.all()
        if not houses_objs:
            return JsonResponse({'errno': 4002, 'errmsg': '无数据'})
        count = houses_objs.count()
        if count < 5:
            houses_objs = houses_objs
        else:
            houses_objs = houses_objs[:5]
        houses_list = []
        for house in houses_objs:
            houses_list.append({
                'house_id': house.id,
                'img_url': house.index_image_url.url,
                'title': house.title
            })
        return JsonResponse({'data': houses_list, "errmsg": "ok", "errno": "0"})


class HouseDetailsView(View):
    def get(self, request, house_id):
        try:
            house = House.objects.get(pk=house_id)
        except House.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '查找不到房子'})
        try:
            orders_list = Order.objects.filter(house_id=house_id)
        except House.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '查找不到订单'})
        comments = []

        for order in orders_list:
            comments.append({
                'comment': order.comment,
                'ctime': str(order.create_time).split(' ')[0],
                'user_name': order.user.username
            })
        house_images = HouseImage.objects.filter(house_id=house_id)
        img_url_list = []
        for house_image in house_images:
            img_url_list.append(
                house_image.url.url
            )
        # 图片为空
        try:
            user_avatar = house.user.avatar.url
        except Exception as e:
            logger.error(e)
            user_avatar = ''

        house_data = {
            "acreage": house.acreage,
            "address": house.address,
            "beds": house.beds,
            "capacity": house.capacity,
            "comments": comments,
            "deposit": house.deposit,
            "facilities": [],
            'hid': house.id,
            'img_urls': img_url_list,
            "max_days": house.max_days,
            "min_days": house.min_days,
            "price": house.price,
            "room_count": house.room_count,
            "title": house.title,
            "unit": house.unit,
            "user_avatar": user_avatar,
            "user_id": house.user_id,
            "user_name": house.user.username
        }

        facilities = house.facility.all()
        for facility in facilities:
            house_data["facilities"].append(facility.id)

        user = request.user
        if not user.is_authenticated:
            user_id = -1
        else:
            user_id = user.id
        return JsonResponse({"errmsg": "OK", "errno": "0", 'data': {"house": house_data, 'user_id': user_id}})
